package com.njy.cloudalibaba.consumer.wrapper;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.njy.pojo.Constant;
import com.njy.utils.Aes128Utils;
import com.njy.utils.RsaSecretUtils;


import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 用于解密request请求参数
 * @RequestBody 读取重写的getInputStream方法
 */
public class SecretRequestWrapper extends HttpServletRequestWrapper {
    private byte[] body;
    private  ByteArrayInputStream byteArrayInputStream;

    public SecretRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        //String method = request.getMethod();

        BufferedReader reader = request.getReader();
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line=reader.readLine())!=null){
            builder.append(line);
        }
        String json = builder.toString();
        JSONObject jsonObject = JSONUtil.parseObj(json);
        String data = (String) jsonObject.get("data");
        String encodeKey = (String) jsonObject.get("key");
        String decodeKey = RsaSecretUtils.privateKeyDecrypt(encodeKey, Constant.RSA_PRIVATE_KEY);
        String decode = Aes128Utils.decode(data, decodeKey);
        body = decode.getBytes();
    }

    /**
     * 返回BufferedReader对象，以字节数据方式读取请求正文.
     * @return
     * @throws IOException
     */
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    /**
     * 返回一个输入流，使用该输入流以二进制方式读取请求正文的内容.
     * @return
     * @throws IOException
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }
}
